package com.xm.xmapp.tool;

import android.util.Log;

import com.xm.xmapp.http.XMURL;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by LDW on 2017/7/14.
 */
public class BeanTool {
    public static byte[] getStr(Object o)  {

        try {
            StringBuilder encodedParams = new StringBuilder();
            StringBuilder str = new StringBuilder();
            Field[] fields = o.getClass().getFields();
            for (int i = 0; i < fields.length; i++) {
                String firstLetter = fields[i].getName();
                Object value = fields[i].get(o);
                if (value != null) {
                    if (!firstLetter.equals("sign")) {
                        encodedParams.append(URLEncoder.encode(firstLetter, "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8")
                                + "&");
                        str.append(firstLetter + "=" + value
                                + "&");
                    }
                }
            }

            str = str.append(XMURL.certkey);
            String sign = md5(str.toString());
            encodedParams.append("sign=" + sign);
            return encodedParams.toString().getBytes("UTF-8");
        } catch (Exception e) {

        }
return  null;
    }


    // 加密方法
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}
